package com.groupbuying.gateway.filter;

/**
 * @author zmlmagic
 * @date 2019/9/19 3:00 PM
 * @company 蒙泰互联网公司
 * @des 备注说明
 **/
import com.groupbuying.gateway.constants.CommonConstants;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Create by liping on 2018/9/11
 * 接口调用日志记录过滤器
 */
@Component
public class LogRecodeFilter extends ZuulFilter {

    private static final Logger logger = LoggerFactory.getLogger(LogRecodeFilter.class);

    @Override
    public String filterType() {
        //要打印返回信息，必须得用"post"
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 2;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        try {
            RequestContext ctx = RequestContext.getCurrentContext();
            HttpServletRequest request = ctx.getRequest();
            String method = request.getMethod();
            String requestUri = request.getAttribute(CommonConstants.ORIGINAL_ADDRESS).toString();
            String remoteHost = request.getRemoteAddr();
            String startTime = request.getAttribute(CommonConstants.YDSTART_TIME).toString();
            long startMill = (Long)request.getAttribute(CommonConstants.YDSTART_MILL);
            int stateCode = ctx.getResponseStatusCode();
//        String outBody = StreamUtils.copyToString(ctx.getResponseDataStream()
//, Charset.forName("UTF-8"));
//        //必须重新写入流
//        //重要！！！
//        ctx.setResponseBody(outBody);
            String content = "\n" + "请求地址:" + requestUri + "\n";
            content = content + "请求耗时:" + (System.currentTimeMillis() - startMill) + "ms";
            content = content + "请求方式:" + method + "\n";
            content = content + "请求开始时间:" + startTime + "\n";
            content = content + "请求结束时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "\n";
            content = content + "请求返回code:" + stateCode + "\n";
            content = content + "请求来源地址:" + remoteHost + "\n";
            logger.info(content);
        } catch (Exception e){

        }
        return null;
    }
}
